/////实现标签页的切换，并确保标签页之间能够进行通信。
// 获取标签页容器和标签页内容容器

// 监听标签页切换事件
function initSwitchTab() {
    let tabSession = document.querySelector('.tab .tab-session');
    let tabFriend = document.querySelector('.tab .tab-friend');

    let lists = document.querySelectorAll('.list');

    tabSession.onclick = function () {
        tabSession.style.backgroundImage = 'url(img/dialog1.png)';
        tabFriend.style.backgroundImage = 'url(img/member.png)';

        lists[0].classList = 'list';
        lists[1].classList = 'list hide';
    }
    
    tabFriend.onclick = function () {
        tabSession.style.backgroundImage = 'url(img/dialog.png)';
        tabFriend.style.backgroundImage = 'url(img/member1.png)';

        lists[0].classList = 'list hide';
        lists[1].classList = 'list';
    }
}

initSwitchTab();

///////////////////////////////////
// webSocket

//let webSocket = new WebSocket('ws://127.0.0.1:8080/websocket');

let webSocket = new WebSocket('ws://'+location.host+'/websocket');
webSocket.onopen = function () {
    console.log('websocket连接成功');
}

webSocket.onmessage = function (event) {
    console.log('收到消息：'+event.data);
    //TODO
    let resp = JSON.parse(event.data);
    if(resp.type == 'message'){
        handleMessage(resp);
    }else{
        //TODO
        //收到其他类型的消息
        console.log('收到其他类型的消息');
    }
}
webSocket.onerror = function () {
    console.log('websocket连接出错');
}

webSocket.onclose = function () {
    console.log('websocket连接关闭');
}

function handleMessage(resp) {
    //将消息插入到会话列表中
    let curLi = findSessionId(resp.sessionId);
    if(curLi == null){
        curLi = createElement('li');
        curLi.setAttribute('message-session-id', resp.sessionId);
        curLi.innerHTML = '<h3>'+resp.fromName+'</h3>'
        + '<p></p>';

        curLi.onclick = function () {
            clickSession(curLi);
        }
    }
    let p = curLi.querySelector('p');
    p.innerHTML = resp.content;
    if(p.innerHTML.length>10){
        p.innerHTML = p.innerHTML.substring(0, 10) + '...';
    }

    //将当前对话插入最上方
    let sessionListUL = document.querySelector('#session-list');
    sessionListUL.insertBefore(curLi, sessionListUL.firstChild);

    //如果当前对话是选中的，则将消息插入到消息展示区域
    if(curLi.className =='selected'){
        addMessage(document.querySelector('.right .message-show'), resp);
        scrollBottom(document.querySelector('.right .message-show'));
    }
}

function findSessionId(target) {
    let sessionLis = document.querySelectorAll('#session-list li');
    for(let li of sessionLis){
        let sessionId = li.getAttribute('message-session-id');
        if(sessionId == target){
            return li;
        }
    }
    return null;
}

function initBotton(){
    let botton = document.querySelector('.right .ctrl');
    let text = document.querySelector('.right .message-input');
    botton.onclick = function () {
        if(!text.value) {
            return;
        }
        let selectedLi = document.querySelector('#session-list .selected');
        if(selectedLi == null){
            return;
        }
        let sessionId = selectedLi.getAttribute('message-session-id');
        let req = {
            type: 'message',
            sessionId: sessionId,
            content: text.value
        }
        webSocket.send(JSON.stringify(req));
        text.value = '';
    }
}
initBotton();

///////////////////////////////////
// 获取用户信息
function getUserInfo() {
    $.ajax({
        type: 'get',
        url: '/user/userInfo',
        success: function (data) {
            console.log(data);
            if(data!=null && data.userId>0){
                let userDiv = document.querySelector('.main .left .user');
                userDiv.innerHTML = data.username;
                userDiv.setAttribute('user-id', data.userId);
            } else {
                alert('当前用户未登录');
                location.assign('login.html');
            }
        }
    });
}

getUserInfo();

// 获取好友列表
function getFriendList() {
    $.ajax({
        type: 'get',
        url: '/friend/friendList',
        success: function (data) {
            console.log(data);
            let friendListUL = document.querySelector('#friend-list');
            friendListUL.innerHTML = '';
            for(let friend of data){
                let friendLi = document.createElement('li');
                friendLi.innerHTML = '<h4>'+friend.friendName+'</h4>';
                friendLi.setAttribute('friend-id', friend.friendId);
                friendListUL.appendChild(friendLi);

                friendLi.onclick = function () {
                    clickFriend(friend);
                }
            }
        },
        error: function () {
            console.log('获取好友列表失败');        
        }
    });
}
getFriendList();

// 获取会话列表
function getSessionList() {
    $.ajax({
        type: 'get',
        url: '/session/sessionList',
        success: function (data) {
            console.log(data);
            let sessionListUL = document.querySelector('#session-list');
            sessionListUL.innerHTML = '';
            for(let session of data){

                let sessionLi = document.createElement('li');
                sessionLi.setAttribute('message-session-id', session.sessionId);
                
                if(session.lastMessage.length>10){
                    session.lastMessage = session.lastMessage.substring(0, 10) + '...';
                }

                sessionLi.innerHTML = '<h3>'+session.friends[0].friendName+'</h3>'
                + '<p>'+session.lastMessage+'</p>';
                sessionListUL.appendChild(sessionLi);

                sessionLi.onclick = function () {
                    clickSession(sessionLi);
                }
            }
        }
    });
}
getSessionList();

function clickSession(li) {
    let allLis = document.querySelectorAll('#session-list>li');
    let sessionId = li.getAttribute('message-session-id');
    for(let curli of allLis){
        if(curli == li){
            li.className = 'selected'
        }else{
            curli.className = '';
        }
    }
    getHistoryMessage(sessionId);
}

//获取历史消息
function getHistoryMessage(sessionId) {
    //1.清空之前的消息
    let titleDiv = document.querySelector('.right .title');
    titleDiv.innerHTML = '';
    let messageShowDiv = document.querySelector('.right .message-show');
    messageShowDiv.innerHTML = '';

    let selectedH3 = document.querySelector('#session-list .selected>h3');
    if(selectedH3){
        titleDiv.innerHTML = selectedH3.innerHTML;
    }
    //2.发送请求获取历史消息
    //3.将历史消息展示到页面上
    //4.展示消息的发送者
    $.ajax({
        type: 'get',
        url: '/message/getMessage?sessionId='+sessionId,
        success: function (data) {
            console.log(data);
            for(let message of data){
                addMessage(messageShowDiv,message);
            }
            scrollBottom(messageShowDiv);
        }
    });
}

function addMessage(messageShowDiv, message) {
    let messageDiv = document.createElement('div');
    let selfUsername = document.querySelector('.left .user').innerHTML;
    if(selfUsername == message.fromName){
        messageDiv.className = 'message message-right';
    }else{
        messageDiv.className = 'message message-left';
    }
    messageDiv.innerHTML = '<div class="box">' +
        '<h4>'+message.fromName+'</h4>' +
        '<p>'+message.content+'</p>' +
        '</div>';
    messageShowDiv.appendChild(messageDiv);
}

function scrollBottom(messageShowDiv) {
    let clientHeight = messageShowDiv.offsetHeight;
    let scrollHeight = messageShowDiv.scrollHeight;
    messageShowDiv.scrollTo(0, scrollHeight - clientHeight);
}

function clickFriend(friend) {
    let sessionLi = findSessionByName(friend.friendName);
    let sessionListUL = document.querySelector('#session-list');
    if(sessionLi){
        sessionListUL.insertBefore(sessionLi, sessionListUL.firstChild);
        //sessionLi.click();
        clickSession(sessionLi);
    }else{
        sessionLi = document.createElement('li');
        sessionLi.innerHTML = '<h3>'+friend.friendName+'</h3>'
        + '<p>'+'</p>';
        sessionListUL.insertBefore(sessionLi, sessionListUL.firstChild);
        sessionLi.onclick = function () {
            clickSession(sessionLi);
        }
        sessionListUL.click();
        //创建会话
        createSession(friend.friendId, sessionLi);
    }
    let tabSession = document.querySelector('.tab .tab-session');
    tabSession.click();
}

function findSessionByName(friendName) {
    let allLis = document.querySelectorAll('#session-list>li');
    for(let sessionLi of allLis){
        let h3 = sessionLi.querySelector('h3');
        if(h3.innerHTML == friendName){
            return sessionLi;
        }
    }
    return null;
}


function createSession(friendId, sessionLi){
    $.ajax({
        type: 'post',
        url: '/session/createSession?toUserId='+friendId,
        success: function (data) {
            console.log('创建会话成功');
            sessionLi.setAttribute('message-session-id', data.sessionId);
        },
        error: function () {
            console.log('创建会话失败');
        }
    })
}



////////////////////////////////////////////////////////////////////////////////
//拓展功能 --- 添加好友
///////////////////////////////////////////////////////////////////////////////
function searchFirends(){
    let searchInput = document.querySelector('.main .left .search input');
    let searchValue = searchInput.value;
    if(searchValue.length>0){
        let botton = document.querySelector('.main .left .search button');
        botton.click() = function () {
            clickSearch(searchValue);
        };
    }
}
//搜索好友
function clickSearch(searchValue){
    let selfUsername = document.querySelector('.left .user').innerHTML;
    if(searchValue.length>0){
        initSwitchRight();
        $.ajax({
            type: 'get',
            url: '/user/search',
            searchValue: searchValue,
            selfUsername: selfUsername,
            success: function (result) {
                console.log(result);
                let titleDiv = document.querySelector('.right .title');
                titleDiv.innerHTML = '';
                titleDiv.innerHTML = '<h3>搜索结果</h3>';
                for(let friendName of result){
                    addFriend(friendName);
                }
            }
        });
    }else{
        alert('请输入搜索内容');
    }
}
//转换页面
function initSwitchRight() {
    let findFriend = document.querySelector('.main .right .findfriend');
    let messageShowDiv = document.querySelector('.main .right .message-show');
    let messageInputDiv = document.querySelector('.main .right .message-input');

    findFriend.classList = 'findfriend';
    messageShowDiv.classList = 'message-show hide';
    messageInputDiv.classList = 'message-input hide';
}
//添加到页面上
function addFriend(friendName) {
    let findFriend = document.querySelector('.main .right .findfriend');
    let friendDiv = document.createElement('li');
    friendDiv.innerHTML = '<h4>'+friendName+'</h4>'
    + '<input class="why">' + '<button>添加</button>';
    friendDiv.onclick = function () {
        clickAdd(friendName);
    }
    findFriend.appendChild(friendDiv);
}

//点击添加按钮
function clickAdd(friendName){
    let inputSeason = document.querySelector('.main .right .findfriend .why');
    if(inputSeason.value.length>0){
        let selfUsername = document.querySelector('.left .user').innerHTML;
        $.ajax({
            type: 'post',
            url: '/friend/addFriend',
            selfUsername: selfUsername,
            friendName: friendName,
            inputSeason: inputSeason.value,
            success: function (data) {
                console.log(data);
                
            }
        })
    }
}

